<template>
  <div class="operation-log-container">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-form">
        <el-form :model="queryForm" :inline="true">
          <el-form-item label="用户名">
            <el-input
              v-model="queryForm.username"
              placeholder="请输入用户名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="操作">
            <el-input
              v-model="queryForm.operation"
              placeholder="请输入操作名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="IP地址">
            <el-input
              v-model="queryForm.ip"
              placeholder="请输入IP地址"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="成功" :value="1" />
              <el-option label="失败" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="warning" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button type="danger" @click="showCleanDialog = true">
              <el-icon><Delete /></el-icon>
              清理日志
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="operation" label="操作" width="150" />
        <el-table-column prop="method" label="请求方法" width="200" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP地址" width="120" />
        <el-table-column prop="executionTime" label="执行时间" width="100">
          <template #default="{ row }">
            <el-tag :type="getExecutionTimeType(row.executionTime)" size="small">
              {{ row.executionTime }}ms
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click.stop="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.page"
          v-model:page-size="queryForm.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 详情弹窗 -->
    <el-dialog v-model="showDetailDialog" title="操作日志详情" width="800px">
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentLog.username }}</el-descriptions-item>
          <el-descriptions-item label="操作">{{ currentLog.operation }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentLog.status === 1 ? 'success' : 'danger'">
              {{ currentLog.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="请求方法" span="2">{{ currentLog.method }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
          <el-descriptions-item label="执行时间">{{ currentLog.executionTime }}ms</el-descriptions-item>
          <el-descriptions-item label="操作时间" span="2">{{ formatDate(currentLog.createdTime) }}</el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentLog.params" class="detail-section">
          <h4>请求参数</h4>
          <el-input
            v-model="currentLog.params"
            type="textarea"
            :rows="6"
            readonly
            class="code-textarea"
          />
        </div>
        
        <div v-if="currentLog.result" class="detail-section">
          <h4>返回结果</h4>
          <el-input
            v-model="currentLog.result"
            type="textarea"
            :rows="6"
            readonly
            class="code-textarea"
          />
        </div>
        
        <div v-if="currentLog.errorMsg" class="detail-section">
          <h4>错误信息</h4>
          <el-alert :title="currentLog.errorMsg" type="error" :closable="false" />
        </div>
        
        <div v-if="currentLog.userAgent" class="detail-section">
          <h4>用户代理</h4>
          <p class="user-agent">{{ currentLog.userAgent }}</p>
        </div>
      </div>
    </el-dialog>
    
    <!-- 清理日志弹窗 -->
    <el-dialog v-model="showCleanDialog" title="清理操作日志" width="400px">
      <el-form :model="cleanForm" label-width="100px">
        <el-form-item label="保留天数">
          <el-input-number
            v-model="cleanForm.days"
            :min="1"
            :max="365"
            placeholder="请输入要保留的天数"
          />
          <div class="form-tip">将删除 {{ cleanForm.days }} 天前的所有日志数据</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCleanDialog = false">取消</el-button>
        <el-button type="danger" :loading="cleanLoading" @click="handleCleanLogs">
          确定清理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Delete } from '@element-plus/icons-vue'
import { operationLogApi } from '@/api/operationLog'
import dayjs from 'dayjs'

const loading = ref(false)
const cleanLoading = ref(false)
const showDetailDialog = ref(false)
const showCleanDialog = ref(false)
const tableData = ref([])
const total = ref(0)
const currentLog = ref(null)
const dateRange = ref([])

const queryForm = reactive({
  page: 1,
  size: 20,
  username: '',
  operation: '',
  ip: '',
  status: null,
  startTime: '',
  endTime: ''
})

const cleanForm = reactive({
  days: 30
})

const formatDate = (date) => {
  if (!date) return ''
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const getExecutionTimeType = (time) => {
  if (time < 500) return 'success'
  if (time < 2000) return 'warning'
  return 'danger'
}

const loadTableData = async () => {
  try {
    loading.value = true
    const response = await operationLogApi.pageOperationLogs(queryForm)
    tableData.value = response.records || []
    total.value = response.total || 0
  } catch (error) {
    console.error('加载操作日志失败:', error)
  } finally {
    loading.value = false
  }
}

const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    queryForm.startTime = dates[0]
    queryForm.endTime = dates[1]
  } else {
    queryForm.startTime = ''
    queryForm.endTime = ''
  }
}

const handleSearch = () => {
  queryForm.page = 1
  loadTableData()
}

const handleReset = () => {
  Object.assign(queryForm, {
    page: 1,
    size: 20,
    username: '',
    operation: '',
    ip: '',
    status: null,
    startTime: '',
    endTime: ''
  })
  dateRange.value = []
  loadTableData()
}

const handleSizeChange = (size) => {
  queryForm.size = size
  queryForm.page = 1
  loadTableData()
}

const handleCurrentChange = (page) => {
  queryForm.page = page
  loadTableData()
}

const handleRowClick = (row) => {
  handleViewDetail(row)
}

const handleViewDetail = async (row) => {
  try {
    const detail = await operationLogApi.getLogById(row.id)
    currentLog.value = detail
    showDetailDialog.value = true
  } catch (error) {
    console.error('获取日志详情失败:', error)
  }
}

const handleExport = async () => {
  try {
    await ElMessageBox.confirm('确定要导出当前查询条件下的日志数据吗？', '提示', {
      type: 'warning'
    })
    
    await operationLogApi.exportLogs(queryForm)
    ElMessage.success('日志导出成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('导出日志失败:', error)
    }
  }
}

const handleCleanLogs = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清理 ${cleanForm.days} 天前的所有日志数据吗？此操作不可恢复！`,
      '危险操作',
      {
        type: 'error',
        confirmButtonText: '确定清理',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    cleanLoading.value = true
    await operationLogApi.cleanOldLogs(cleanForm.days)
    
    ElMessage.success('日志清理成功')
    showCleanDialog.value = false
    loadTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理日志失败:', error)
    }
  } finally {
    cleanLoading.value = false
  }
}

onMounted(() => {
  loadTableData()
})
</script>

<style scoped lang="scss">
.operation-log-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.log-detail {
  .detail-section {
    margin-top: 20px;
    
    h4 {
      margin-bottom: 10px;
      color: #303133;
      font-weight: 600;
    }
    
    .code-textarea {
      font-family: 'Courier New', monospace;
      
      :deep(.el-textarea__inner) {
        font-family: 'Courier New', monospace;
        background-color: #f5f7fa;
      }
    }
    
    .user-agent {
      padding: 10px;
      background-color: #f5f7fa;
      border-radius: 4px;
      font-size: 12px;
      color: #606266;
      word-break: break-all;
    }
  }
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}
</style>